package com.swordxu.yim.android.imlib.proto;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.swordxu.yim.android.config.ProtocolConstant;
import com.swordxu.yim.android.imlib.network.packet.base.DefaultHeader;
import com.swordxu.yim.android.imlib.network.packet.base.Header;
import com.swordxu.yim.android.imlib.network.packet.base.Packet;
import com.swordxu.yim.android.log.Logger;


/**
 * MsgServerPacket:请求(返回)登陆消息服务器 yugui 2014-05-04
 */

public class MsgServerPacket extends Packet {

	private Logger logger = Logger.getLogger(MsgServerPacket.class);

	public MsgServerPacket() {
		// todo eric remove this
		setNeedMonitor(true);
	}

	public MsgServerPacket(PacketRequest.Entity entity) {
		mRequest = new PacketRequest(entity);
		setNeedMonitor(true);
	}

	@Override
	public String encode() {
        Header header = mRequest.getHeader();
        PacketRequest req = (PacketRequest) mRequest;
        if (null == req) {
            return null;
        }
        JSONObject jo = new JSONObject();
        jo.put("header", header);

        jo.put("body",  JSON.toJSON(((PacketRequest) mRequest).entity));
		return jo.toJSONString();
	}

    @Override
    public void decode(String buffer) {
        if (null == buffer)
            return;
        try {
            PacketResponse res = new PacketResponse();

            JSONObject jo = JSON.parseObject(buffer);
            Header header = new Header();
            header = jo.getObject("header", Header.class);
            res.setHeader(header);
            res.entity = jo.getObject("body", res.entity.getClass());
            this.mResponse = res;
        } catch (Exception e) {
            logger.e("packet#decode exception:%s", e.getMessage());
            logger.e(e.getMessage());
        }
    }

	public static class PacketRequest extends Request {
		public static class Entity {
			public int userType;
		}
		public Entity entity;
		public PacketRequest(Entity entity) {
			this.entity = entity;
			Header header = new DefaultHeader(ProtocolConstant.SID_LOGIN, ProtocolConstant.CID_LOGIN_REQ_MSGSERVER);
			setHeader(header);
		}
	}

	public static class PacketResponse extends Response {
		public static class Entity {
			public int result;
			public String ip1;
			public String ip2;
			public short port;
		}

		public Entity entity = new Entity();
	}
}
